package com.njtoyo.taxi.admin.logic.business.simple_call;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.njtoyo.taxi.admin.library.taxi_service.SimpleCallTaxiService;
import com.njtoyo.taxi.admin.mapper.master.entity.SimpleCallBacklog;
import com.njtoyo.taxi.admin.mapper.master.enums.SimpleCallBacklogState;
import com.njtoyo.taxi.admin.mapper.master.mapper.SimpleCallBacklogMapper;
import com.njtoyo.taxi.admin.utils.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class SimpleCallBackLogic {

    @Autowired
    private SimpleCallBacklogMapper simpleCallBacklogMapper;

    @Autowired
    private SimpleCallTaxiService simpleCallTaxiService;

    @Async
    public void sendSimpleCallBacklog(Long id) {
        log.info("正在自动发送电召订单 {}", id);
        SimpleCallBacklog backlog = simpleCallBacklogMapper.selectById(id);
        if (Objects.isNull(backlog)) {
            log.info("电召数据不存在 {}", id);
            return;
        }
        if (!backlog.getState().equals(SimpleCallBacklogState.init)) {
            log.info("电召数据已被处理 {}", backlog);
            return;
        }
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("adCode", backlog.getAdCode());
        requestBody.put("mobileNumber", backlog.getMobileNumber());
        requestBody.put("url", backlog.getAudioUrl());
        requestBody.put("adminId", AuthUtil.getUserInfo().getId());
        if (Objects.nonNull(backlog.getAreaIds())) {
            requestBody.put("areaIds", backlog.getAreaIds());
        }
        Long callId = simpleCallTaxiService.send(requestBody);
        if (Objects.isNull(callId)) {
            log.info("电召单发送失败");
            return;
        }
        new LambdaUpdateChainWrapper<>(simpleCallBacklogMapper)
                .eq(SimpleCallBacklog::getId, id)
                .set(SimpleCallBacklog::getCallId, callId)
                .set(SimpleCallBacklog::getState, SimpleCallBacklogState.done)
                .update();

        log.info("电召单系统自动发单成功,呼叫id为 {}", callId);
    }
}
